/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.auth.business;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import reportcenter.auth.dominio.Users;
import reportcenter.support.dbutil.JPAFactory;

/**
 *
 * @author renan_luz
 */
public class UserAuthorizationDao {

    public List<Users> getAll() {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();

        List<Users> users = null;
        try {
            Query query = JPAFactory.getInstance().getManager().createNamedQuery("Users.findAll");
            users = query.getResultList();
            

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
        return getAllFrom(users);
    }
    
    private List<Users>getAllFrom(List<Users> users){
        List<Users> retorno = new ArrayList<Users>();
        for(Users u:users){
            if (u.getEnabled() == 1){
                u.setBoolEnabled(true);
            }
            retorno.add(u);
        }
        return retorno;
    }

    public void add(Users users) {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {
            System.out.println("ENABLED -> " + users.isBoolEnabled());
            if(users.isBoolEnabled()){
                users.setEnabled((short)1);
            }else{
                users.setEnabled((short)0);
            }
            JPAFactory.getInstance().getManager().persist(users);
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
    }


    public void delete(Users users) {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {

            JPAFactory.getInstance().getManager().remove(users);

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
    }
    
     public void update(Users users) {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {
            if(users.isBoolEnabled()){
                users.setEnabled((short)1);
            }
            JPAFactory.getInstance().getManager().persist(users);
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
    }
}
